using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using S.M.SmartMedical.API.Read.Application.Query;
using S.M.SmartMedical.Domain.DTOs;
using S.M.SmartMedical.Domain.Entities;
using S.M.SmartMedical.ErrorCode;
using S.M.SmartMedical.Infrastructure;

namespace S.M.SmartMedical.API.Read.Application.Handler
{
    /// <summary>
    /// 获取轮播图列表查询处理器
    /// </summary>
    public class GetCarouselListHandler : IRequestHandler<GetCarouselListQuery, APIResult<PagedResult<CarouselDto>>>
    {
        private readonly MyDbContext _context;
        private readonly IMapper _mapper;
        private readonly ILogger<GetCarouselListHandler> _logger;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="context">数据库上下文</param>
        /// <param name="mapper">对象映射器</param>
        /// <param name="logger">日志记录器</param>
        public GetCarouselListHandler(
            MyDbContext context,
            IMapper mapper,
            ILogger<GetCarouselListHandler> logger)
        {
            _context = context;
            _mapper = mapper;
            _logger = logger;
        }

        /// <summary>
        /// 处理获取轮播图列表查询
        /// </summary>
        /// <param name="request">查询请求</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>轮播图列表结果</returns>
        public async Task<APIResult<PagedResult<CarouselDto>>> Handle(GetCarouselListQuery request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始处理获取轮播图列表查询，页码：{PageIndex}，页大小：{PageSize}",
                    request.Query.PageIndex, request.Query.PageSize);

                // 构建查询
                var query = _context.Carousels
                    .Where(c => !c.IsDeleted);

                // 根据标题过滤
                if (!string.IsNullOrWhiteSpace(request.Query.Title))
                {
                    query = query.Where(c => c.Title.Contains(request.Query.Title));
                }

                // 根据状态过滤
                if (request.Query.Status.HasValue)
                {
                    query = query.Where(c => c.Status == request.Query.Status.Value);
                }

                // 按排序号升序排序
                query = query.OrderBy(c => c.SortOrder);

                // 获取总记录数
                var totalCount = await query.CountAsync(cancellationToken);

                // 分页查询
                var carousels = await query
                    .Skip((request.Query.PageIndex - 1) * request.Query.PageSize)
                    .Take(request.Query.PageSize)
                    .ToListAsync(cancellationToken);

                // 映射为DTO
                var carouselDtos = _mapper.Map<List<CarouselDto>>(carousels);

                var result = new PagedResult<CarouselDto>
                {
                    Items = carouselDtos,
                    TotalCount = totalCount,
                    PageIndex = request.Query.PageIndex,
                    PageSize = request.Query.PageSize
                };

                _logger.LogInformation("获取轮播图列表查询处理完成，总记录数：{TotalCount}", totalCount);

                return new APIResult<PagedResult<CarouselDto>>
                {
                    Code = APIEnum.OK,
                    Message = "获取轮播图列表成功",
                    Data = result
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取轮播图列表查询处理异常");
                return new APIResult<PagedResult<CarouselDto>>
                {
                    Code = APIEnum.Fail,
                    Message = "获取轮播图列表失败，系统异常",
                    Data = null!
                };
            }
        }
    }
}